import {
    uploadFile,
    getPartnerList,
    getEmployeeList,
    getPhraseList,
    addrIdentify,
    getZoneInfo,
    
} from "@/apis/common.js";

import {
    orderAdd,
    getOrderParam,
    getRepairTypeList,
    getOrderSrcList,
    getRepairCatgList,
} from "@/apis/workOrder.js";

import {
	deepClone
} from "@/util";

export default {
    data() {
        return {
            editId: '',
            photosMaxQty: 5,
            showPhrase: false,
            showSalesmanCommission: false,
            showSalesman: false,
            showCustomer: false,
            showCustomerType: false,
            showRepairType: false,
            showRepairCatg: false,
            showAppointment: false,
            phraseList: [],
            appointment: '',
            custTypeList: ['公司', '家庭'],
            repairCatg: [],
            repairType: [],
            serviceList: [{}],
            currEmployee: '',
            employeeParams: {
                PageSize: 10,
                PageNo: 1,
                DeptId: '',
                GroupId: '',
                EmpName: '',
            },
            employeeList: [],
            partnerParams: {
                PageSize: 10,
                PartnerName: '',
                PageNo: 1,
                PartnerAttr: 'cust',
            },
            partnerName: '',
            partnerList: [],

            showAddress: false,
            addrText:'',
            showRegionPicker: false,
            columns: [],
            columnData: [],
            provinces: [],
            zoneInfo: [],

            formHeightList: [],
            tabsStyle: {
                activeStyle: {
                    color: '#F65D30',
                    fontWeight: 'bold',
                    transform: 'scale(1.05)'
                },
                inactiveStyle: {
                    color: '#333333',
                    transform: 'scale(1)'
                }
            },
            currTab: 0,
            tabList: [{
                name: '客户信息'
            }, {
                name: '工单信息'
            }, {
                name: '服务信息'
            },
                // {
                //     name: '费用明细'
                // },
            ],
            imageList: [],
            orderForm: {
                Descr: '', // 下单记录
                AppointmentDate: '',
                AppointmentTime: '',
                SalerCharge: '',
                RewardAmount: '',
                TGID: '',
                VirtCharge1: '',
                VirtCharge2: '',
                VirtCharge3: '',
                VirtCharge4: '',
                VirtCharge5: '',
                Employee1: '',
                Employee2: '',
                Employee3: '',
                Employee4: '',
                Employee5: '',
                CustId: '',
                CustName: '',
                Zone1: '',
                Zone2: '',
                Zone3: '',
                Tel: '', //电话
                Zone5: '',
                Contact: '', //联系人
                Zone1_2: '',
                Zone2_2: '',
                Zone3_2: '',
                Tel2: '',
                Zone5_2: '', //详细地址
                Contact2: '',
                CallPhotos: [],
                Remark1: '',
                Remark2: '',
                Remark3: '',
                Remark4: '',
                Remark5: '',
                ItemId: '',
                ItemName: '',
                ItemStyle: '',
                ItemBrand: '',
                ItemCatg: '',
                SerialNo: '',
                BuyDate: '',
                ExpaireDate: '',
                OrderSrc: '',
                OrderNo: '',        // 来源单号
                CustType: '',       // 客户类型
                RepairType: '',     //  服务类型
                Saler: '',          // 业务员
                Priority: false,
                RepairCatg: '',     // 服务分类
                lnkRegion: '',      //区域
            },
            orderRules: {
                Tel: [{
                    required: true,
                    message: '请输入手机号',
                    trigger: ['change', 'blur'],
                },
                {
                    validator: (rule, value, callback) => {
                        return uni.$u.test.mobile(value);
                    },
                    message: '手机号码不正确',
                    trigger: ['change', 'blur'],
                }
                ],
                Contact: {
                    required: true,
                    message: '请输入联系人姓名',
                    trigger: ['blur', 'change']
                },
            },
            fileList4: [],
        };
    },
    // onPageScroll(res) {
    // 	console.log('onPageScroll', res)

    // },
    onLoad(option){
        this.fetchZoneInfo()
        this.fetchPartnerList()
        this.fetchEmployeeList()
        this.fetchPhraseList()
        this.fetchOrderAddInit()
    },
    
    mounted() {
        setTimeout(() => {
            uni.pageScrollTo({
                scrollTop: 0,
                duration: 0
            });
            this.tabList = this.tabList.map((item, idx) => {
                uni.createSelectorQuery().select(".formTitleRef_" + idx).boundingClientRect((
                    res) => {
                    console.log('formTitleRef_0', res, res.top)
                    item.top = res.top
                    console.log('return', item)

                }).exec()
                return item
            })
            console.log('this.tabList', this.tabList)

        }, 0)
    },
    methods: {
        async handleOrderAdd(){
            if (!await this.$refs.form1.validate()) return;
            console.log('orderForm',this.orderForm,this.appointment)
            const orderForm = deepClone(this.orderForm)
            
            orderForm.CallPhotos = orderForm.CallPhotos? orderForm.CallPhotos.join(',') : ''
            // orderForm.Priority = orderForm.Priority ? '加急' : ''
            orderForm.TGID = orderForm.TGID ? parseInt(orderForm.TGID) : ''
            
            orderForm.Saler = this.employeeList.find(o => o.EmpName === orderForm.Saler)?.EmpId || ''
            orderForm.Employee1 = this.employeeList.find(o => o.EmpName === orderForm.Employee1)?.EmpId || ''
            orderForm.Employee2 = this.employeeList.find(o => o.EmpName === orderForm.Employee2)?.EmpId || ''
            orderForm.Employee3 = this.employeeList.find(o => o.EmpName === orderForm.Employee3)?.EmpId || ''
            orderForm.Employee4 = this.employeeList.find(o => o.EmpName === orderForm.Employee4)?.EmpId || ''
            orderForm.Employee5 = this.employeeList.find(o => o.EmpName === orderForm.Employee5)?.EmpId || ''

            console.log('salersalersalersalersaler',orderForm)
            const appointment = this.appointment
            if(appointment){
                const at = appointment.split(' ')
                orderForm.AppointmentDate = at[0]
                orderForm.AppointmentTime = at[1]
            }
            if(orderForm.CustType == ''){
                orderForm.CustType = 0
            }else{
                orderForm.CustType = orderForm.CustType == '公司' ? 1 : 2
            }
            console.log('handleOrderAdd-----', orderForm) 
            const res = await orderAdd(orderForm)
            console.log('handleAdd res', res)
            
            if (res.MsgCode != 0) return
            uni.showToast({
                title:'新增成功',
                icon: "none",
                mask: true,
                position: "center",
            });
            setTimeout(() => {
                this.$navigateBack(this.$router, 1)
            }, 1000)

        },
        async handleAddrIdentify(){
            const res = await addrIdentify({Addr:this.addrText})
            if (res.MsgCode != 0) return
            console.log('handleAddrIdentify', res)
            const addrInfo = res.data.AddrInfo
            const orderForm = this.orderForm
            orderForm.Contact = addrInfo.Contact ? addrInfo.Contact : orderForm.Contact
            orderForm.Tel = addrInfo.Tel ? addrInfo.Tel : orderForm.Tel
            orderForm.Zone5 = addrInfo.Zone5 ? addrInfo.Zone5 : orderForm.Zone5
            orderForm.Zone1 = addrInfo.ProvName ? addrInfo.ProvName : orderForm.Zone1
            orderForm.Zone2 = addrInfo.CityName ? addrInfo.CityName : orderForm.Zone2
            orderForm.Zone3 = addrInfo.TownName ? addrInfo.TownName : orderForm.Zone3
            this.orderForm = orderForm
            this.orderForm.lnkRegion = `${orderForm.Zone1},${orderForm.Zone2},${orderForm.Zone3}`
            this.showAddress = false
            uni.showToast({
                title: '解析成功',
                icon: "sucess",
                mask: true,
                position: "center",
            });
        },
        handleServicePick(key){
            console.log('handleServicePick',key)
            this.currEmployee = key
            this.showSalesman = true
        },
        async fetchOrderAddInit() {
            const accountInfo = uni.getStorageSync('accountInfo') || {}
            const CmpyCode = accountInfo.currCmpy ? accountInfo.currCmpy.CmpyCode : ''
            const rtRes = await getRepairTypeList({CmpyCode})
            const rcRes = await getRepairCatgList({CmpyCode})
            // const orRes = await getOrderSrcList({CmpyCode})

            console.log('fetchOrderAddInit', rtRes)
            this.repairType = rtRes.data.RepairTypeList
            this.repairCatg = rcRes.data.RepairCatgList
            
        },
        async fetchPhraseList() {
            const res = await getPhraseList({})
            if (res.MsgCode != 0) return
            console.log('fetchPhraseList', res)
            this.phraseList = res.data.PhraseList

        },
        handleEmployeeSearch() {
            this.employeeParams.PageNo = 1
            this.employeeList = []
            this.fetchEmployeeList()
        },
        scrolltoEmployeeLower() {
            this.employeeParams.PageNo = this.employeeParams.PageNo + 1
            this.fetchEmployeeList()

        },
        async fetchEmployeeList() {
            const res = await getEmployeeList(this.employeeParams)
            if (res.MsgCode != 0) return
            console.log('fetchEmployeeList', res)

            this.employeeList = [...this.employeeList, ...res.data.EmployeeList]
        },
        hanleCusthange(idx){
            console.log('hanleCusthange',idx)
            const item = this.partnerList[idx]
            this.orderForm.CustName = item.PartnerName
            this.orderForm.CustId = item.PartnerId
        },
        handlePartnerSearch() {
            this.partnerParams.PageNo = 1
            this.partnerList = []
            this.fetchPartnerList()
        },
        scrolltoPartnerLower() {
            this.partnerParams.PageNo = this.partnerParams.PageNo + 1
            this.fetchPartnerList()

        },
        async fetchPartnerList() {
            const res = await getPartnerList(this.partnerParams)
            if (res.MsgCode != 0) return
            console.log('fetchPartnerList', res)
            this.partnerList = [...this.partnerList, ...res.data]
        },
        handleDatetimeConfirm(e) {
            this.showAppointment = false
            console.log('handleDatetimeConfirm', e.value, e.mode)
            const timeFormat = uni.$u.timeFormat
            setTimeout(() => {
                this.appointment = timeFormat(e.value, 'yyyy-mm-dd hh:MM')
            }, 0);

        },
        handlePickerConfirm(e) {
            // const addrForm = this.addrForm
            // addrForm.ProvID = this.zoneInfo[e.indexs[0]].id
            // addrForm.CityID = this.zoneInfo[e.indexs[0]].citys[e.indexs[1]].id
            // addrForm.TownID = this.zoneInfo[e.indexs[0]].citys[e.indexs[1]].towns[e.indexs[2]].id
            // addrForm.currPickedVal = e.value.join('')

            // this.addrForm = addrForm
            console.log('handlePickerConfirm', e)
            this.showRegionPicker = false
            this.orderForm.Zone1 = e.regions[0]
            this.orderForm.Zone2 = e.regions[1]
            this.orderForm.Zone3 = e.regions[2]
            this.orderForm.lnkRegion = e.value.join()
            
        },
        
        async fetchOrderParam() {
			const res = await getOrderParam()
			if (res.MsgCode != 0) return
			console.log('fetchOrderParam', res)
            const opData = res.data
            this.photosMaxQty = opData.CallPhotosMaxQty
            const zoneInfo = this.zoneInfo
            const pi = zoneInfo.findIndex(o => o.id === opData.DefaultProvId)
            const provIdx = pi != -1 ? pi : 0
            const ci = zoneInfo[provIdx].citys.findIndex(o => o.id === opData.DefaultCityId)
            const cityIdx = ci != -1 ? ci : 0
            const ti = zoneInfo[provIdx].citys[cityIdx].towns.findIndex(o => o.id === opData.DefaultTownId)
            const townIndex = ti != -1 ? ti : 0
            this.$refs['addrPicker'].changeHandler({detail:{value: [provIdx, 0, 0]}})
            this.$refs['addrPicker'].changeHandler({detail:{value: [provIdx, cityIdx, 0]}})
            this.$refs['addrPicker'].changeHandler({detail:{value: [provIdx, cityIdx, townIndex]}})
            this.$refs['addrPicker'].confirm()            
		},
        async fetchZoneInfo() {
			const res = await getZoneInfo()
			if (res.MsgCode != 0) return
			console.log('fetchZoneInfo', res)
			const provinces = []
			const zoneInfo = res.data.map(item => {
				provinces.push(item.name)
				item.cityList = item.citys.map(cItem => {
					cItem.townList = cItem.towns.map(tItem => {
						return tItem.name
					})
					return cItem.name
				})
				return item
			})
			this.zoneInfo = zoneInfo
			this.columns = [provinces, zoneInfo[0].cityList, zoneInfo[0].citys[0].townList]
            this.fetchOrderParam()

		},
        handleTabChange(item) {
            console.log('handleTabChange', item, this.formHeightList)
            const tabTop = this.tabList[item.index].top
            uni.pageScrollTo({
                scrollTop: tabTop - 44,
                duration: 200
            });
        },
        async afterRead(event) {
            console.log('afterRead', event, this.imageList)
            this.imageList = [...this.imageList, ...event.file]
            event.file.map(async item => {
                await this.uploadImg(item.url)
            })
        },
        async uploadImg(imgUrl) {
            const accountInfo = uni.getStorageSync('accountInfo') || {}
            const data = {
                name: 'file',
                formData: {},
                fileUrl: imgUrl
            }
            const res = await uploadFile({
                CmpyCode: accountInfo.currCmpy ? accountInfo.currCmpy.CmpyCode : ''
            }, data)
            console.log('uploadImg', res)
            if (res.MsgCode != 0) return
            this.orderForm.CallPhotos.push(res.FileName)
        },
        deletePic(event) {
            this.imageList.splice(event.index, 1)
            this.orderForm.CallPhotos.splice(event.index, 1)
            console.log('deletePic', this.imageList, this.orderForm.CallPhotos)
        },
    }
}
